package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.common.util.TreeUtil;
import cn.angis.db.service.BaseService;
import cn.angis.system.mapper.ResourceMapper;
import cn.angis.system.model.Resource;
import cn.angis.system.model.Roleres;
import cn.dev33.satoken.stp.StpUtil;
import org.beetl.sql.core.SqlId;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Cache;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 资源表服务
* @author angis.cn
* @Date 2023-01-05
*/
@ProxyComponent
public class ResourceService extends BaseService<ResourceMapper, Resource> {
    /**
     * 根据用户id获取资源权限列表
     * @param userId
     * @return: List<String>
     * @throws: 
     * @Date: 2023/1/8     
     */
    @Cache
    public List<String> selectResourcesCodeByUserId(String userId) {
        StringBuilder sb = new StringBuilder();
        return baseMapper.getSQLManager().select(SqlId.of("resource.selectResourcesCodeByUserId"), String.class, Map.of("userId", userId));
    }

    @Cache
    public List<Resource> listByUserId() {
        String userId = StpUtil.getLoginId("");
        return TreeUtil.listToTree(baseMapper.getSQLManager().select(SqlId.of("resource.listByUserId"), Resource.class, Map.of("userId", userId)));
    }

    @Cache
    public List<Resource> getRouterList() {
        return baseMapper.getSQLManager().lambdaQuery(Resource.class)
                .andIsNotNull(Resource::getPermission)
                .andIsNotNull(Resource::getRoutePath)
                .andIsNotNull(Resource::getHttpMethod)
                .andEq(Resource::getResStatus, Constant.ENABLE)
                .orderBy(Resource::getResSort)
                .select(Resource::getPermission, Resource::getRoutePath, Resource::getHttpMethod);
    }

    public List<Resource> getResourceTreeList() {
        List<Resource> resourcesList = baseMapper.getSQLManager().lambdaQuery(Resource.class)
                .orderBy(Resource::getResSort)
                .select();
        return TreeUtil.listToTree(resourcesList);
    }

    @Cache
    public List<Resource> getMenuList() {
        List<Resource> resourcesList = baseMapper.getSQLManager().lambdaQuery(Resource.class)
                .andIn(Resource::getType, Arrays.asList(Constant.DISABLE, Constant.MENU))
                .orderBy(Resource::getResSort)
                .select();
        return TreeUtil.listToTree(resourcesList);
    }

    public List<String> getResourceIdListByRoleId(String roleId) {
        return baseMapper.getSQLManager().lambdaQuery(Roleres.class)
                .andEq(Roleres::getRoleId, roleId)
                .select().stream().map(Roleres::getResId)
                .collect(Collectors.toList());
    }
}